<?php
defined('BASEPATH') or exit('No direct script access allowed');
session_start();

class Login extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model("user_model");
        $this->load->helper('url');
    }

    public function index()
    {
        $data["title"] = "登陆页面";
        $this->load->view("login/login", $data);
    }

    public function login()
    {
        if (isset($_SESSION["user"])) {
            redirect("dashboard");
        } else {
            $this->load->helper('form');
            $this->load->library('form_validation');

            $this->form_validation->set_rules("username", "username", "required");
            $this->form_validation->set_rules("password", "password", "required");
            if ($this->form_validation->run() === FALSE) {
                $this->index();
            } else {
                $user = $this->user_model->getOneUserByUsername($this->input->post("username"));
                if (!isset($user)) {
                    redirect("login");
                } else {
                    $password = $this->input->post("password");
                    $base64_password = base64_encode(strval($password) . strval($user["salt"]));
                    if (strlen($base64_password) >= 100) {
                        $base64_password = substr($base64_password, 0, 100);
                    }
                    if ($base64_password == $user["password"]) {
                        $_SESSION["user"] = $user;
                        redirect("dashboard");
                    } else {
                        redirect("login");
                    }
                }
            }
        }
    }

    public function logout()
    {
        session_destroy();
        redirect("login");
    }
}

?>